package cn.wanho.config.service;

import cn.wanho.dto.ExamMenuRole;
import cn.wanho.dto.ExamUser;
import cn.wanho.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: heyang
 * @Description:
 * @Date Create in 2022/8/05jmkh 14:36
 */
public class UserDetailsServiceImpl implements UserDetailsService {
    //通过拿到用户和当前该用户的权限就可以包装成一共 UserDetails接口---User对象
    @Autowired
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username == null || "".equals(username)) {
            throw new RuntimeException("用户不能为空");
        }
        //根据用户名查询用户
        ExamUser examUser = userService.selectByName(username);
        if (examUser == null) {
            throw new RuntimeException("用户不存在");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (examUser != null) {
            //获取该用户所拥有的权限
            List<ExamMenuRole> examMenuRoles = userService.selectListByUser(examUser.getId());
            // 声明用户授权
//            sysPermissions.forEach(sysPermission -> {
//                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode());
//                grantedAuthorities.add(grantedAuthority);
//            });
            for(ExamMenuRole menuRole: examMenuRoles){
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(menuRole.getRolePath());
                grantedAuthorities.add(grantedAuthority);
            }
        }
        //这个User不是我定义的，而是Ss给你写好的
        return new User(examUser.getUserName() ,examUser.getUserPass(),
                true, true, true, true, grantedAuthorities);
    }
}
